import java.io.*;

public class FileUtil {
    public static final String SEPARATE_FIELD="\n";
    public static final String SEPARATE_LINE="\n";

    public static void savebook(Diary diary){
        String name="黑马笔记本.txt";

        InputStream in=null;

        try {
            in=new FileInputStream(name);
            if (in!=null){
                in.close();
                createFile(name,true,diary);
            }
        }catch (FileNotFoundException e){
            createFile(name,false,diary);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void createFile(String name, boolean label,Diary diary){
        BufferedOutputStream out=null;
        StringBuffer sbf=new StringBuffer();

        try {
            if (label){
                out=new BufferedOutputStream(new FileOutputStream(name,true));
            }else {
                out=new BufferedOutputStream(new FileOutputStream(name));
                String fieldsSort="欢迎来到黑马日记本";
                sbf.append(fieldsSort).append(SEPARATE_FIELD);
            }
            sbf.append("时间:").append(diary.time);

            sbf.append("姓名：").append(diary.name).append(SEPARATE_LINE);
            sbf.append("标题：").append(diary.title).append(SEPARATE_LINE);
            sbf.append("天气：").append(diary.weather).append(SEPARATE_FIELD);
            sbf.append("内容").append(diary.content).append(SEPARATE_FIELD);

            String str=sbf.toString();
            byte[]b=str.getBytes();

            for (int i=0;i<b.length;i++){
                out.write(b[i]);
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out!=null){
                    out.close();}
            }catch (Exception e2){
                e2.printStackTrace();
            }
        }
        }



        public static void readFile()throws Exception{
        FileInputStream in=new FileInputStream("黑马日记本.txt");
        byte[]b=new byte[in.available()];
        in.read(b);
        String str=new String(b);
            System.out.println(str);
            in.close();
        }
}
